package com.sam.spring.security.compent;

import com.sam.spring.security.dto.UserDetail;
import com.sam.spring.security.entity.User;
import com.sam.spring.security.service.MenuService;
import com.sam.spring.security.service.RoleService;
import com.sam.spring.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @classname: CustomUserDetailService
 * @description: TODO
 * @Author: sam
 * @date: 2021/7/10 22:13
 */
@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userService.getByUserName(userName);
        if (user == null){
            throw new UsernameNotFoundException("该用户不存在！");
        }
        // 获取角色列表
        List<String> roleList = roleService.getListByUserName(userName);

        // 获取该用户所拥有的权限
        List<String> authorities = menuService.queryMenuByRoleCods(roleList);

        List<String> roleCodes = roleList.stream().map(item -> "ROLE_" + item).collect(Collectors.toList());
        authorities.addAll(roleCodes);

        UserDetail detail = new UserDetail();
        detail.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",",authorities)));
        detail.setUsername(user.getUsername());
        detail.setPassword(user.getPassword());

        return detail;
    }
}
